package 力扣.链表;

public class 合并两个有序链表21 {
    /**
     * 垃圾版：分开比较
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode tail = dummy;

        while (l1 != null || l2 != null){
            if (l1 == null){
                tail.next = l2;
                return dummy.next;
            }else if (l2 == null){
                tail.next = l1;
                return dummy.next;
            }

            if (/*l1 != null && l2 != null &&*/ l1.val <= l2.val){
                tail.next = l1;
                l1 = l1.next;
            }else {
                tail.next = l2;
                l2 = l2.next;
            }
            tail = tail.next;
        }
        //养成收尾的好习惯
        tail.next = null;
        return dummy.next;

    }

    /**
     * 进阶版：合并在一块进行比较
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode tail = dummy;

        while (l1 != null || l2 != null){
            if (l1 == null || l2 != null && l1.val > l2.val){
                tail.next = l2;
                l2 = l2.next;
            }else {
                tail.next = l1;
                l1 = l1.next;
            }
            tail = tail.next;
        }
        //养成收尾的好习惯
        tail.next = null;
        return dummy.next;
    }
}
